package by.dezhits.liltweets.content;

import org.json.JSONException;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import by.dezhits.liltweets.R;
import by.dezhits.liltweets.bo.Tweet;
import by.dezhits.liltweets.db.DBHelper;

public class SearchResultTweetsProvider extends ContentProvider {

	private DBHelper dbHelper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		dbHelper = new DBHelper(getContext(), null);
		return true;
	}

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		dbHelper.clearSearchResultTweetsTable();
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		String jsonData = values.getAsString(getContext().getString(R.string.data));
		Tweet tweet;
		try {
			tweet = new Tweet(jsonData);
			dbHelper.addTweet(tweet, DBHelper.SEARCH_RESULT_TWEETS_TABLE);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor tweets = dbHelper.getSearchResultTweets(selection,selectionArgs,sortOrder);
		tweets.setNotificationUri(getContext().getContentResolver(), uri);
		return tweets;	
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

}
